﻿#include <ThostFtdcMdApi.h>
#include "MdUserSpi.h"
#include <list>
#include <string>
#include <vector>
#include "Tools.h"
#include "SymbolDetail.h"
#include <iostream>
#include "CTPTime.h"
#ifdef __linux__
#include <cstring>
#endif
#include "MainSymbolGather.h"
#include "CTPLoginAccount.h"
#include "OptionManager.h"

// 此工程的任务为行情监听
int main(int argc, char *argv[])
{
	// 非行情时间段直接退出
	time_t ctTime = Tools::GetCurrentTimeStamp();
	CTPTm::HolidayManager pManager;
	if (!pManager.IsMarketTime(ctTime))
	{
		return 88;
	}
	MarketDataManager m_marketManager;
	CMdUserSpi mdSpi(m_marketManager);
	CThostFtdcMdApi *pApi = CThostFtdcMdApi::CreateFtdcMdApi("", false, false);
	// 初始化后的登录请求
	std::string mdSettingFile = OptionManager::Instance().GetCTPMDAccountSettingFile();
	CTPLogin::MDAccount mdAccount(QString::fromLocal8Bit(mdSettingFile.c_str()));
	mdSpi.SetFrontConnectedFunc([pApi, &mdAccount]() {
		CThostFtdcReqUserLoginField pBody;
		strncpy(pBody.BrokerID, mdAccount.GetBrokerID().c_str(), sizeof(TThostFtdcBrokerIDType));
		strncpy(pBody.UserID, mdAccount.GetUserID().c_str(), sizeof(TThostFtdcInvestorIDType));
		strncpy(pBody.Password, mdAccount.GetPassword().c_str(), sizeof(TThostFtdcPasswordType));
		int res = pApi->ReqUserLogin(&pBody, 111);
		printf("请求登录--%d\n", res);
	});
	// 登录后的回调
	mdSpi.SetLoginedFunc([pApi, &mdSpi](CThostFtdcRspUserLoginField* pRspUserLogin, CThostFtdcRspInfoField* pRspInfo, int nRequestID, bool bIsLast) {
		std::list<std::string> symbolNameList;
		MainSymbolGather::Instance().GetToRegSymbols(symbolNameList);
		//symbolNameList.emplace_back("a2109");
		SymbolPackage::SymbolListToChar changer(symbolNameList);
		//订阅
		int res = pApi->SubscribeMarketData(changer.GetSymbolArray(), changer.GetSymbolsSize());
		printf("订阅合约--%d\n", res);
	});
	// 取消行情的回调
	MainSymbolGather::Instance().SetUnSubscribeFunc([pApi](const std::list<std::string> &pList) {
		SymbolPackage::SymbolListToChar changer(pList);
		//订阅
		int res = pApi->UnSubscribeMarketData(changer.GetSymbolArray(), changer.GetSymbolsSize());
		//printf("取消订阅合约--%d\n", res);
	});

	// 注册回调
	pApi->RegisterSpi(&mdSpi);
	// 注册网络地址
	std::list<std::string > address;
	mdAccount.GetUrlList(address);
	for (auto iter = address.begin(); iter != address.end(); ++iter)
	{
		pApi->RegisterFront((char*)iter->c_str());
	}
	// 初始化连接
	pApi->Init();
	//pApi->Join();
	m_marketManager.LoopWait();

	return 0;
}
